<template>
	<view class="container" @click="legendShow = false">
		<map class="map" id="map" ref="map"
		enable-3D
		enable-rotate
		enable-overlooking
		subkey='LFZBZ-MLI6R-KV7W3-WNDT5-NEZFH-76FLT'
		layer-style="2"
		:latitude='latitude'
		:longitude='longitude'
		:scale="scale" 
		:markers="newMarkers" 
		@markertap="chooseMarker"
		 @regionchange='regionchange'
		show-location></map>
		
		<uni-search-bar
		@confirm="getkeyword" 
		@clear="getkeyword" :bigSearch="true" ref='searchBar'></uni-search-bar>
		<!-- 数量统计 -->
		<view class="statisticsBox flex_between_row">
			<view>燃气报警<text>{{alarmSum}}</text>起</view>
			<view>设备异常<text>{{abnormalSum}}</text>起</view>
		</view>
	
		<!-- 地图定位、缩放控件 -->
		<view class="selfPosBox" :style="bottomStyle" hover-class="halfOpacity" @click='moveToSelfLocation(16)' >
			<image src="../../../static/img/map/pos.png" mode=""></image>
		</view>
		<view class="scaleBox"  :style="bottomStyle">
			<view hover-class="halfOpacity" @click='changeScale(true)'>
				<image src="../../../static/img/map/bigger.png" mode=""></image>
			</view>
			<view hover-class="halfOpacity" @click='changeScale(false)'>
				<image src="../../../static/img/map/smaller.png" mode=""></image>
			</view>
		</view>
		<!-- 地图筛选控件 -->
		<view class="layer_box flex_around_column" >
			<view class="flex_around_column" hover-class="halfOpacity" @click="showFilter">
				<image src="../../../static/img/map/filter.png" mode=""></image>
				<text>筛选</text>
			</view>
			<view class="flex_around_column" hover-class="halfOpacity" @click.stop="legendShow = !legendShow">
				<image src="../../../static/img/map/legend.png" mode=""></image>
				<text>图例</text>
			</view>
		</view>
		<popup-layer v-if="filterShow" ref="popupRef" :direction="'left'">
			<view class="typeBox">
				<type-tab :title="'报警级别'" :tabs.sync="alarmTypes"></type-tab>
				<type-tab :title="'运行状态'" :tabs.sync="runStatus"></type-tab>
			</view>
		</popup-layer>
		
		<!-- 图例详情 -->
		<view class="legendWrap flex_between_column" :class="{'legendShow':legendShow}">
			<view class="legendBox" v-for="(item,key) of legend" :key='key'>
				<view class="tit">{{key}}</view>
				<view v-for="(item2,i) in legend[key]" :key='i' class="con">
					<image :src="item2.src" mode=""></image>
					<text>{{item2.txt}}</text>
				</view>
			</view>
		</view>
		<!-- 报警、设备详情 -->
		<monitor-item-detail v-if="monitorDetail" ref="monitorDetail"></monitor-item-detail>
		<realtime-monitor-item-detail v-if="showRealtimeMonitorDetail" ref="showRealtimeMonitorDetail"></realtime-monitor-item-detail>
	</view>
</template>

<script>
import { mixin } from '../../../common/mixins.js';
// let amapFile = require('../../libs/amap-wx.js'); //引入高德js
let vm;


const deviceIconPathGood = `../../../static/img/alarm/device_checked.png`;
const deviceIconPathBad = `../../../static/img/alarm/device_alarm.png`;

const SCALE_LEVEL = 1;


// 节流 定时器方案
function throttle(fn,wait){
    var timer = null;
    return function(){
        var context = this;
        var args = arguments;
        if(!timer){
            timer = setTimeout(function(){
                fn.apply(context,args);
                timer = null;
            },wait)
        }
    }
}
    

export default {
	mixins:[mixin],
	data() {
		return {
			endScale:3,
			isOnHide:false,
			isOnLoad:false,
			mapContext:null,
			abnormalSum:0,
			alarmSum:0,
			keyword:'',
			legendShow:false,
			legend:{
				燃气报警:[{
					src:'../../../static/img/alarm/alarm_level1.png',
					txt:'1级'
				},{
					src:'../../../static/img/alarm/alarm_level2.png',
					txt:'2级'
				},{
					src:'../../../static/img/alarm/alarm_level3.png',
					txt:'3级'
				}],
				设备运行:[
					{
						src:deviceIconPathGood,
						txt:'正常'
					},
					{
						src:deviceIconPathBad,
						txt:'异常'
					}
				]
			},
			level:'',
			status:'',
			scale: 2,
			showRealtimeMonitorDetail: false, // 默认不展示监测详情
			monitorDetail: false, // 默认不展示设备详情
			key: '9e794c3f3803c391c37b1a815f05a504',
			markers: [],
			newMarkers: [],
			latitude: '',
			longitude: '',
			textData: {},
			filterShow: false,
			alarmTypes: [
				{
					id: 1,
					value: '1级（高）',
					checked: false
				},
				{
					id: 2,
					value: '2级（中）',
					checked: false
				},
				{
					id: 3,
					value: '3级（低）',
					checked: false
				},
				{
					id: 0,
					value: '无报警',
					checked: false
				}
			],
			runStatus:[
				{
					id: 'normal',
					value: '设备正常',
					checked: false
				},
				{
					id: 'pump',
					value: '泵转速异常',
					checked: false
				},
				{
					id: 'dryer',
					value: '干燥剂失效',
					checked: false
				},
				{
					id: 'voltage',
					value: '电量不足',
					checked: false
				},
				{
					id: 'soak',
					value: '设备浸水',
					checked: false
				},
				{
					id: 'move',
					value: '设备移动',
					checked: false
				},
				{
					id: 'laser',
					value: '传感器异常',
					checked: false
				},
				{
					id: 'gps',
					value: 'GPS缺失',
					checked: false
				},
				{
					id: 'temperature',
					value: '温度异常',
					checked: false
				},
				{
					id: 'network',
					value: '通讯异常',
					checked: false
				}
			],
		};
	},
	computed:{
		bottomStyle(){
			if(this.monitorDetail){
				return 'bottom:480rpx'
			}else if(this.showRealtimeMonitorDetail){
				return 'bottom:480rpx'
			}else{
				return 'bottom:20rpx'
			}
		}
	},
	watch: {
		scale(newVal){
			if(newVal<3){
				this.scale = 3
			}
			if(newVal> 20){
				this.scale = 20
			}
		},
		markers:{
			handler(newVal){
				this.newMarkers = this.unique(newVal, 'id');
				// console.log('去重后的newMarkers-->',this.newMarkers)
			},
			deep:true
		},
		alarmTypes: {
			handler(newVal) {
				vm = this;
				let arr = [];
				newVal.forEach(item => {
					if (item.checked) {
						arr.push(item.id);
					}
				});
				this.level = arr.join(',');
				// if (arr.length == vm.alarmTypes.length) {
				// 	this.level = '';
				// }
				this.initMap()
				.then(markers => {
					this.showMarkers(markers)
				})
			},
			deep: true,
		},
		runStatus: {
			handler(newVal) {
				//console.log('runStatus',JSON.stringify(newVal))
				this.transformArrToStr(newVal, 'status');
				this.initMap()
				.then(markers => {
					this.showMarkers(markers)
				})
			},
			deep: true
		},
	},
	onLoad(options) {
		vm = this;
		//console.log('map onLoad')
		this.mapContext = uni.createMapContext('map', this);
		
		
		
		
		uni.getLocation({
			type:'gcj02'
		})
	},
	onHide() {
		this.isOnHide = true
		this.$refs.searchBar.clear()
	},
	async onShow() {
		this.isOnHide = false
		//console.log('map onShow')
		
		// this.mapContext.initMarkerCluster({
		// 	enableDefaultStyle:true,
		// 	zoomOnClick:true,
		// 	gridSize:60,
		// 	complete(res){
		// 		//console.log('initMarkerCluster',res)
		// 	}
		// })
		vm.getLocationSetting()
		
		vm.$nextTick(()=>{
			
			vm.initMap().then(markers => {
				vm.showMarkers(markers)
				uni.getStorage({
					key:'curMarkerId',
					success(res){
						vm.chooseMarker({
							detail:{
								markerId:res.data
							}
						})
					},
					fail() {
						uni.getLocation({
							type:'gcj02',
							success(res) {
								setTimeout(() => {
									vm.longitude = res.longitude
									vm.latitude = res.latitude
								 }, 300)
								vm.moveToSelfLocation(3)
							}
						})
					}
				})
				
			})
		})
		
		
	},

	mounted() {
	
	},
	methods: {
		// 定位获取位置信息授权逻辑
		getLocationSetting() {
		   //wx.getSetting是获取用户授权的信息的，除了应用在位置信息授权还能应用在用户信息授权等等
		   uni.getSetting({
		       success: res => {if (res.authSetting['scope.userLocation'] !== undefined && res.authSetting['scope.userLocation'] !== true) {
		               //console.log('不是第一次进入该页面,且未授权')
		               uni.showModal({
		                   title: '是否授权当前位置',
		                   content: '需要获取您的地理位置，请确认授权，否则无法实现相关功能！',
		                   success: res => {
		                       //如果点击取消则显示授权失败
		                       if (res.cancel) {
		                           uni.showToast({
		                           	icon:'none',
									title:'您已拒绝授权!'
		                           })
		                       }
		                       //如果点击确定会打开授权页请求二次授权
		                       else if (res.confirm) {
		                           uni.openSetting({
		                               success: dataAu => {
		                                   if (dataAu.authSetting['scope.userLocation'] === true) {
											   uni.showToast({
											   	icon:'success',
											   	title:'授权成功!'
											   })
		                                       //再次授权，调用getLocationt的API
		                                       // this.handleLoacation()
		                                   } else {
											   uni.showToast({
											   	icon:'none',
											   	title:'授权失败!'
											   })
		                                   }
		                               }
		                           })
		                       }
		                   }
		               })
		           }
		       },
		       fail: err => {
		           // this.isLocation = false
		           uni.showModal({
		               title: '提示',
		               content: '未知错误，请重新打开小程序！'
		           })
		       }
		   })
		},
		regionchange(e){
			if(e.type == 'end'){
				this.mapContext.getScale({
					success(res){
						vm.endScale = parseInt(res.scale)
						console.log('vm.endScale',vm.endScale)
					}
				})
			}
		},
		moveToSelfLocation(scale){ //回到自己位置
			this.mapContext.moveToLocation({
				success(){
					vm.scale = scale;
				}
			})
		},
		moveToLocation(lon,lat){
			uni.getLocation({
				type:'gcj02',
				success(res) {
					setTimeout(() => {
						vm.longitude = lon
						vm.latitude = lat
						vm.scale = 16;
					 }, 300)
					
				vm.mapContext.moveToLocation({
					longitude: lon,
					latitude: lat
				});
			}
		})
			
		},
		changeScale(val){
			throttle(this.handleScale(val),1000)
		},
		handleScale(val){
			this.mapContext.getCenterLocation()
			.then(res => {
				vm.latitude = res.latitude
				vm.longitude = res.longitude
				if(val){
					vm.scale += SCALE_LEVEL
				}else{
					vm.scale -= SCALE_LEVEL
				}
			})
		},
		unique(arr, attrName) {
			const res = new Map();
			return arr.filter(a => !res.has(a[attrName]) && res.set(a[attrName], 1));
		},
		getkeyword(data) {
			
			
			vm.keyword = data.value
			// uni.showLoading()
			vm.scale = 5;
			vm.monitorDetail = false;
			vm.showRealtimeMonitorDetail = false;
			vm.level = ''
			vm.status = ''
			
			if(vm.isOnHide) return
			
			vm.initMap()
			.then(markers => {
				vm.showMarkers(markers)
				// uni.hideLoading()
			})

		},
		showFilter() {
			this.filterShow = true;
			this.$nextTick(function(){
				this.$refs.popupRef.show(); // 或者 filterShow = rue
			})
			
		},
		close() {
			this.$refs.popupRef.close(); // 或者 filterShow = false
		},
		// 点击图标
		chooseMarker(e) {
			let curMarker = null
			console.log('点击了图标-》',e.detail.markerId)
			if(e.detail.markerId){
				uni.setStorage({
					key:'curMarkerId',
					data:e.detail.markerId
				})
			}
			vm.markers.forEach((item,index) => {
				item['width'] = 35
				item['height'] = 35
				if(e.detail.markerId == item.id){
					curMarker = vm.markers[index]
					
					curMarker['width'] = 45
					curMarker['height'] = 45
				    
					vm.moveToLocation(curMarker.longitude,curMarker.latitude)
				}
			})
			console.log('点击了图标-》curMarker',curMarker)
			if (['正常','异常'].indexOf(curMarker.state) > -1) {
				// 设备点位
				this.showRealtimeMonitorDetail = true;
				this.monitorDetail = false;
				uni.setStorage({
					key:'equipId',
					data:curMarker.equipId,
					success() {
						
						setTimeout(()=>{
							vm.$refs.showRealtimeMonitorDetail.init();
						},300)
						
						uni.removeStorage({
							key:'monitorDetail',
						})
					}
				})
				

			} else {
				this.monitorDetail = true;
				this.showRealtimeMonitorDetail = false;
				uni.setStorage({
					key: 'monitorDetail',
					data: curMarker,
					success() {
						setTimeout(()=>{
							vm.$refs.monitorDetail.init();
						},300)
						
						uni.removeStorage({
							key:'realtimeMonitorDetail'
						})
					}
				});
			}
		},
		initMap() {
			
			vm.showRealtimeMonitorDetail = false;
			vm.monitorDetail = false;
			// if(vm.showRealtimeMonitorDetail || vm.showRealtimeMonitorDetail){
			// 	vm.scale = 5;
			// }else{
			// 	vm.scale = 16;
			// }
			return new Promise((resolve,reject) => {
					vm.$api
						.getEquipViewMap({
							alarmLevel: vm.level,
							runStatus:vm.status,
							search:vm.keyword,
							userName: vm.$store.state.user.userInfo.nickName
						})
						.then(res => {
							vm.abnormalSum = res.data.data.abnormalSum
							vm.alarmSum = res.data.data.alarmSum
							if(!res.data.data.equip.length){
								uni.showToast({
									title:res.data.msg
								})
								vm.markers = [];
								return
							}
							
						    resolve(res.data.data.equip)
						});
				})
		},
		showMarkers(markersArr) {
			vm.markers = [];
			let iconPath = ''
			
			markersArr.forEach((item, index) => {
				
				if(!item.latitude || !item.longtitude){
					iconPath = ''
				}else{
					
					if(['正常','异常'].includes(item.state)){ //报警图标
						item.state=='正常'?iconPath = deviceIconPathGood :iconPath = deviceIconPathBad
					}else { //设备图标
						iconPath = `../../../static/img/alarm/alarm_level${item.alarmLevel}.png`
					}
					vm.markers.push({
						// title,
						id: item.markerId,
						latitude: item.latitude || '',
						longitude: item.longtitude || '',
						iconPath,
						width: 35,
						height: 35,
						alarmId: item.alarmId || '',
						equipId: item.equipId || '',
						alarmLevel: item.alarmLevel || '',
						installPos:item.installPos || '',
						equipmentCode:item.equipmentCode || '',
						alarmInspect:item.alarmInspect || '',
						state:item.state || '',
						// joinCluster:true,
						// clusterId:1
					});
					
					
					// vm.mapContext.addMarkers({
					// 	markers
					// })
					
				}
				// let title = '甲烷浓度超标报警'
				
			});
			// console.log('vm.markers',vm.markers)
		}
	}
};
</script>

<style lang="scss">
	monitor-item-detail,
	realtime-monitor-item-detail,
	uni-search-bar,
	.layer_box,
	.item_detail_box{
		z-index: 999;
	}
	
.map {
	width: 100%;
	height: 100vh;
}
.layer_box {
	position: absolute;
	right: $uni-spacing-col-36;
    top: 110rpx;
    height: 184rpx;
    width: 72rpx;
	box-shadow: $uni-boxshadow;
	background: #fff;
	border-radius: $uni-border-radius-base;
	padding: 10rpx 0;
	image {
		width: 40rpx;
		height: 40rpx;
	}
	text{
		color: $uni-text-color-disable;
		font-size: 20rpx;
	}
}
uni-search-bar {
	position: absolute;
	top: 28rpx;
	left: $uni-spacing-col-36;
	right: $uni-spacing-col-36;
	width: calc(100% - 72rpx);
	border-radius: 10rpx;
	border: none;
	box-shadow: 0 0 15rpx 5rpx #DCEBF9;
	.uni-searchbar__box{
		border-radius: 10rpx !important;
	}
}
.scaleBox{
	z-index: 999;
	position: absolute;
	background: #fff;
	border-radius: $uni-border-radius-base;
	text-align: center;
	width: 72rpx;
	height: 144rpx;
	right: $uni-spacing-col-36;
	transition: all .3s;
	display: flex;
	flex-direction: column;
	justify-content: space-around;
	box-shadow: $uni-boxshadow;
	align-items: center;
	view{
		height: 52rpx;
		width: 100%;
		&:first-child{
			margin-bottom: 20rpx;
			line-height: 82rpx;
		}
	}
	image{
		height: 26rpx;
		width: 26rpx;
	}
}
.selfPosBox{
	position: absolute;
	width: 72rpx;
	height: 72rpx;
	left: $uni-spacing-col-36;
	transition: all .3s;
	display: flex;
	justify-content: center;
	align-items: center;
	box-shadow: $uni-boxshadow;
	border-radius: $uni-border-radius-base;
	background: #fff;
	z-index: 999;
	image{
		width: 36rpx;
		height: 36rpx;
	}
}
.statisticsBox{
	position: absolute;
	top: 110rpx;
	padding: 0 20rpx;
	left: $uni-spacing-col-36;
	height: 50rpx;
	border-radius: 50rpx;
	background: #fff;
	color: $uni-text-color-disable;
	view{
		font-size: 12px;
		&:first-child{
			margin-right: 42rpx;
		}
	}
	&::before{
		content: '';
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		top: 12rpx;
		height: 30rpx;
		width: 2rpx;
		background: #ccc;
	}
	text{
		color: #4187F1;
		margin: 0 8rpx;
	}
}
.legendWrap{
	position: absolute;
	top: 210rpx;
	right: -220rpx;
	box-shadow: $uni-boxshadow;
	background: #fff;
	border-radius: $uni-border-radius-base;
	padding:14rpx 28rpx 14rpx 14rpx;
	transition: all .3s;
	image{
		height: 44rpx;
		width: 44rpx;
		margin-right: 5rpx;
	}
	.legendBox{
		margin-bottom: 20rpx;
		.tit{
			font-size: 28rpx;
			color: $uni-text-color-black;
			margin-bottom: 10rpx;
			text-indent: 10rpx;
		}
		&:last-child{
			margin-bottom: 0;
		}
		.con{
			display: flex;
			align-items: center;
			margin-bottom: 5rpx;
		}
	}
	text{
		color: $uni-text-color-disable;
		font-size: 20rpx;
	}
}
.legendShow{
	right: 120rpx;
}
.typeBox{
	width: 66vw;
	padding-top: 30rpx;
}
</style>
